package com.hao.redis.client;

import java.util.List;

import redis.clients.jedis.Jedis;


public class Container {
	

	/**
	 * 从节点获取内容
	 */
	public static String get(String key) {
		Jedis jedis = JedisClient.getInstance().getJedis();
			try {
				String result = jedis.get(key);
				JedisClient.getInstance().returnResource(jedis);
				return result;
			} catch (Exception e) {
				JedisClient.getInstance().returnBrokenResource(jedis);
			} 
		
		return null;
	}
	
	/**
	 * 多个key从当前节点获取内容
	 * 
	 */
//	public Object[] getMultiArray(String... keys) {
//		String[] enKeys = new String[keys.length];
//		for (int i=0;i<keys.length;i++){
//			enKeys[i] = formatKey(keys[i]);
//		}
//		MemCachedClient client = getClient();
//		Object[] o = client.getMultiArray(enKeys);
//		
//		return o;
//	}
	
	/**
	 * memcache client多个key获取存在bug，改为单个key获取
	 * @param keys
	 * @return
	 */
	public static List<String> getMultiArray(String... keys) {
		if(keys.length == 0) {
			return null;
		}
		String[] enKeys = new String[keys.length];
		for (int i=0;i<keys.length;i++){
			enKeys[i] = keys[i];
		}

		try {
			Jedis jedis = JedisClient.getInstance().getJedis();
			try {
				List<String> result = jedis.mget(enKeys);
				JedisClient.getInstance().returnResource(jedis);
				
				return result;
			} catch (Exception e) {
				JedisClient.getInstance().returnBrokenResource(jedis);
			} 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	/**
	 * 所有节点存储
	 * @param key
	 * @param o
	 * @return
	 */
	public static boolean push(String key, String o, int expiry) {
		boolean result = false;
		String enkey = key;
		Jedis jedis = JedisClient.getInstance().getJedis();
		try {
			for (int i=0; i < 10; i++){ //如果失败最多执行10次,每次暂停50毫秒
				try {
					result = JedisClient.SUCCESS_FLAG.equals(jedis.set(enkey, o));
					if(expiry > 0) {
						jedis.expire(enkey, expiry);
					}
					if (result){
						break;
					}
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			JedisClient.getInstance().returnResource(jedis);
		}
		return result;
	}
	
	
	public static boolean push(String key, String o) {
		return push(key, o, 0);  //实体数据默认永不过期
	}
	
	
	/**
	 * 移除所有节点
	 */
	public static boolean remove(String key)
	{
		boolean result = true;
		Jedis jedis = JedisClient.getInstance().getJedis();
		try {
			result = jedis.del(key) > 0;
		} finally {
			JedisClient.getInstance().returnResource(jedis);
		}
		return result;
	}

	
	
}
